package com.autonavi.notify;


import java.util.HashMap;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

/**
 * *
 *
 * @author winter *
 */
public class AdTools {

	/**
	 * AD 验证
	 *
	 * @param userName
	 * @param passWord
	 * @return
	 */
	public static boolean adTrueOrFalse(String userName, String passWord) {
		String url = new String("ldap://autonavi.com:389");
		Hashtable env = new Hashtable();
		DirContext ctx;
		env.put(Context.SECURITY_AUTHENTICATION, "simple");
		env.put(Context.SECURITY_PRINCIPAL, "min.zhan");
		env.put(Context.SECURITY_CREDENTIALS, "1qaz2wsx#EDC");
		env.put(Context.INITIAL_CONTEXT_FACTORY,
				"com.sun.jndi.ldap.LdapCtxFactory");
		env.put(Context.PROVIDER_URL, url);
		try {
			ctx = new InitialDirContext(env);
			ctx.close();
			// System.out.println("验证成功!");
			return true;
		} catch (NamingException err) {
			err.printStackTrace();
			// System.out.println("验证失败!");
			return false;
		}
	}

	// 使用LDAP验证密码
	public static void main(String[] args) {
		String userName = "min.zhan"; // 用户名称
		String passwd = "1qaz2wsx#EDC";
		String host = "autonavi.com"; // AD服务器
		String port = "389"; // 端口
		String domain = "@autonavi.com"; // 邮箱的后缀名
		String url = new String("ldap://" + host + ":" + port);
		String user = userName.indexOf(domain) > 0 ? userName : userName
				+ domain;
		Hashtable<String, String> env = new Hashtable<String ,String>();
		DirContext ctx = null;
		env.put(Context.SECURITY_AUTHENTICATION, "simple");
		env.put(Context.SECURITY_PRINCIPAL, user);
		if ("".equals(passwd.trim())) {
			passwd = null;
			System.out.println("密码不能为空!!");
		}
		env.put(Context.SECURITY_CREDENTIALS, passwd);
		env.put(Context.INITIAL_CONTEXT_FACTORY,
				"com.sun.jndi.ldap.LdapCtxFactory"); // LDAP工厂类
		env.put(Context.PROVIDER_URL, url);
		try {
			ctx = new InitialDirContext(env);
			ctx.close();
			System.out.println("验证成功!!");
		} catch (NamingException e) {
			e.printStackTrace();
			System.out.print("验证失败!!");
		}
	}
}
